package com.htgd.gardenexpo.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.service.*;
import com.htgd.gardenexpo.utils.UniteUtils;
import com.htgd.gardenexpo.vo.GisTitleCoordinate;
import com.htgd.gardenexpo.vo.ValueLabel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author ：hejing
 * @date ：Created in 2021/5/24 17:24
 * @description：GIS游客服务资源管理
 * @menu: GIS游客服务资源管理
 * @modified By：`
 * @version: 1.0
 */
@RestController
@RequestMapping("/api/gis")
@Slf4j
@Api(tags = "GIS游客服务资源管理")
public class GISResourcesController {

    @Value("${upload.absolute.url}")
    public String absolute_url;
    @Value("${upload.absolute.audio}")
    public String absolute_audio;
    @Value("${upload.url}")
    public String upload_url;
    @Value("${local.url}")
    public String local_url;
    @Value("${spring.file-storage.aws-s3[0].bucket-name}")
    public String bucket_name;


    @Resource
    private GeConGisresourceService geConGisresourceService;

    @Resource
    private GeConGisresourceTypeService geConGisresourceTypeService;

    @Resource
    private GeConGisresourceAreaService geConGisresourceAreaService;

    @Resource
    private GeConGisresourceUploadService geConGisresourceUploadService;

//    @Autowired
//    private FileStorageService fileStorageService;
//
//    @Resource
//    private GetAmazonS3Client getAmazonS3Client;

    @Autowired
    private GeConSceneService geConSceneService;

    /**
     * 添加服务资源分类
     */
    @PostMapping(value = "/add")
    public CommonResult<JSONObject> add(@RequestBody GeConGisresourceType geConGisresourceType){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geConGisresourceTypeService.insert(geConGisresourceType);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 编辑资源分类
     */
    @PostMapping(value = "/edit")
    public CommonResult<JSONObject> edit(@RequestBody GeConGisresourceType geConGisresourceType){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geConGisresourceTypeService.update(geConGisresourceType);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除资源分类
     */
    @PostMapping(value = "/delete")
    public CommonResult<JSONObject> delete(int gisTypeId){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            List<GeConGisresource> list =geConGisresourceService.queryByTypeId(gisTypeId);
            if (list!=null&&list.size()>0){
                result.setCode(300);
                result.setMessage("该分类下有景点，无法删除");
                return  result;
            }
            geConGisresourceTypeService.deleteById(gisTypeId);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }


    /**
     * 批量删除资源分类
     */
//    @PostMapping(value = "/deleteByIds")
    public CommonResult<JSONObject> deleteByIds(String gisTypeIds){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            for (String gisTypeId:gisTypeIds.split(",")){
                CommonResult<JSONObject> result1=delete(Integer.parseInt(gisTypeId));
                if (result1.getCode()==300){
                    result.setCode(300);
                    result.setMessage("选中的分类中有分类下有景点，无法删除");
                    return result;
                }
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取资源分类列表
     */
    @GetMapping(value = "/list")
    public CommonResult<List<GeConGisresourceType>> list(PageQuery pageQuery){
        CommonResult<List<GeConGisresourceType>> result = new CommonResult<>();
        try {
            PageInfo<GeConGisresourceType> list = geConGisresourceTypeService.pageList(pageQuery);
            result.setCode(200);
            result.setData(list.getList());
            result.setMessage(String.valueOf(list.getTotal()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 上传文件
     */
    @PostMapping(value = "/uploadFile")
    public GeConGisresourceUpload uploadFile(@RequestParam(value = "file") MultipartFile file) throws IOException {

        GeConGisresourceUpload geConGisresourceUpload = new GeConGisresourceUpload();
        if (file.isEmpty()) {
            System.out.println("文件为空");
        }

        BufferedImage image = ImageIO.read(file.getInputStream());
        int width = 0 ;
        int height = 0;
        if (image != null) {
            width = image.getWidth();
            height = image.getHeight();
        }

        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = absolute_url; // 上传后的路径
        fileName = UUID.randomUUID() + "@" + width +"@"+ height +"@"+ suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        geConGisresourceUpload.setFilePath(local_url+"upload/"+fileName);
        geConGisresourceUploadService.insert(geConGisresourceUpload);
        return geConGisresourceUpload;
    }

    /**
     * 上传音频文件
     */
    @PostMapping(value = "/uploadAudio")
    public String uploadAudio(@RequestParam(value = "file") MultipartFile file) throws Exception{

//        //使用指定的存储平台
//        FileInfo fileInfo=fileStorageService.of(file)
//                .setPlatform("aws-s3-1")
//                .upload();
//        return upload_url+fileInfo.getFilename();
        if (file.isEmpty()) {
            System.out.println("文件为空");
        }

        BufferedImage image = ImageIO.read(file.getInputStream());
        int width = 0 ;
        int height = 0;
        if (image != null) {
            width = image.getWidth();
            height = image.getHeight();
        }

        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = absolute_audio; // 上传后的路径
        fileName = UUID.randomUUID() + "@" + width +"@"+ height +"@"+ suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return local_url+"audio/"+fileName;
    }



    /**
     * 添加服务资源（包含名称、坐标、图标、图文简介、音视频链接）
     */
    @Transactional
    @PostMapping(value = "/addSource")
    public CommonResult<JSONObject> addSource(@RequestBody GeConGisresource geConGisresource){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            List<GeConGisresource> list=geConGisresourceService.queryByName(geConGisresource.getGisTitle());
            if (list!=null&&list.size()>0){
                result.setCode(300);
                result.setMessage("名称重复!");
                return result;
            }
            geConGisresourceService.insert(geConGisresource);
            GeConScene geConScene = new GeConScene();
            if (!geConGisresource.getUploadIds().equals("")){
                for (String uploadId:geConGisresource.getUploadIds().split(",")){
                    GeConGisresourceUpload geConGisresourceUpload = geConGisresourceUploadService.queryById(Integer.parseInt(uploadId));
                    geConScene.setThumbnail(geConGisresourceUpload.getFilePath());
                    geConGisresourceUpload.setGisId(geConGisresource.getGisId());
                    geConGisresourceUploadService.update(geConGisresourceUpload);
                }
            }
            if(Objects.equals(geConGisresource.getGisResourceTypeId(),33)){
                geConScene.setTitle(geConGisresource.getGisTitle());
                geConScene.setContent(geConGisresource.getIntroduction());
                geConScene.setIsTop(geConGisresource.getIsTop());
                geConScene.setRecommendType(geConGisresource.getRecommendType());
                geConScene.setCreateUserId(geConGisresource.getCreateUserId());
                geConScene.setCreateUser(geConGisresource.getCreateUser());
                geConSceneService.save(geConScene);
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
            result.setMessage("保存失败");
        }
        return result;
    }

    /**
     * 编辑服务源
     */
    @PostMapping(value = "/editSource")
    public CommonResult<JSONObject> editSource(@RequestBody GeConGisresource geConGisresource){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            GeConGisresource geConGisresource1=geConGisresourceService.queryById(geConGisresource.getGisId());
            if (!geConGisresource.getGisTitle().equals(geConGisresource1.getGisTitle())){
                List<GeConGisresource> list=geConGisresourceService.queryByName(geConGisresource.getGisTitle());
                if (list!=null&&list.size()>0){
                    result.setCode(300);
                    result.setMessage("名称重复!");
                    return result;
                }
            }
            String uploadIds=geConGisresource.getUploadIds();
            geConGisresourceService.update(geConGisresource);
            if (!uploadIds.equals("") && uploadIds.contains(",")) {
                geConGisresourceUploadService.deleteByIds(uploadIds.split(","), geConGisresource.getGisId());
                for (String uploadId : uploadIds.split(",")) {
                    GeConGisresourceUpload geConGisresourceUpload = geConGisresourceUploadService.queryById(Integer.parseInt(uploadId));
                    geConGisresourceUpload.setGisId(geConGisresource.getGisId());
                    geConGisresourceUploadService.update(geConGisresourceUpload);
                }
            }else if(!uploadIds.equals("")){//一个文件
                List<GeConGisresourceUpload> geConGisresourceUploads = geConGisresourceUploadService.queryByGisId(geConGisresource.getGisId());
                if(geConGisresourceUploads.size()>0){
                    geConGisresourceUploadService.deleteNotById(Integer.valueOf(uploadIds),geConGisresource.getGisId());
                    //删除以后再查一遍
                    GeConGisresourceUpload geConGisresourceUpload = geConGisresourceUploadService.queryById(Integer.parseInt(uploadIds));
                    geConGisresourceUpload.setGisId(geConGisresource.getGisId());
                    geConGisresourceUploadService.update(geConGisresourceUpload);
                }else {//全部上传
                    if (!geConGisresource.getUploadIds().equals("")){
                        for (String uploadId:geConGisresource.getUploadIds().split(",")){
                            GeConGisresourceUpload geConGisresourceUpload = geConGisresourceUploadService.queryById(Integer.parseInt(uploadId));
                            geConGisresourceUpload.setGisId(geConGisresource.getGisId());
                            geConGisresourceUploadService.update(geConGisresourceUpload);
                        }
                    }
                }
            }
            else {
                geConGisresourceUploadService.deleteByGisId(geConGisresource.getGisId());
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除服务源
     */
    @PostMapping(value = "/deleteSource")
    public CommonResult<JSONObject> deleteSource(int gisId){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geConGisresourceService.deleteById(gisId);
//            List<GeConGisresourceUpload> list=geConGisresourceUploadService.queryByGisId(gisId);
//            for (GeConGisresourceUpload geConGisresourceUpload:list){
//                String filepath=geConGisresourceUpload.getFilePath();
////                String path=filepath.substring(filepath.indexOf(bucket_name+"/"),filepath.length()-1);
////                getAmazonS3Client.delete(path);
//            }
            geConGisresourceUploadService.deleteByGisId(gisId);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取服务源列表
     */
    @GetMapping(value = "/sourcelist")
    public CommonResult<List<GeConGisresource>> sourcelist(PageQuery pageQuery){
        CommonResult<List<GeConGisresource>> result = new CommonResult<>();
        try {
            pageQuery.setPageSize(0);
            List<GeConGisresource> list=geConGisresourceService.queryAllByValue(pageQuery);
            if (list!=null&&list.size()>0){
                for (GeConGisresource geConGisresource:list){
                    if (geConGisresource.getGisDescrition()!=null){
                        String content= UniteUtils.stripHtml(geConGisresource.getGisDescrition().toString());
                        if (!content.equals("")){
                            geConGisresource.setGisDescrition(content.substring(0,content.length()>200?200:content.length()));
                        }else {
                            geConGisresource.setGisDescrition("");
                        }
                    }
                }
            }
            result.setCode(200);
            result.setData(list);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     *  服务源详情
     */
    @GetMapping(value = "/sourcedetails")
    public CommonResult<Map<String,Object>> sourcedetails(int gisId){
        log.info("gis-点位详情：{}",gisId);
        CommonResult<Map<String, Object>> result = new CommonResult<>();
        try {
            Map<String,Object> map=new HashMap<>();
            GeConGisresource geConGisresource=geConGisresourceService.queryById(gisId);
            map.put("gis",geConGisresource);
            List<GeConGisresourceUpload> list=geConGisresourceUploadService.queryByGisId(gisId);
            map.put("upload",list);
            result.setCode(200);
            result.setData(map);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     *  获取服务简介
     */
    @GetMapping(value = "/getserviceinfo")
    public CommonResult<List<Map<String,Object>>> getserviceinfo(){
        CommonResult<List<Map<String, Object>>> result = new CommonResult<>();
        return result;
    }


    /**
     * 新增区域
     */
    @PostMapping(value = "/addArea")
    public CommonResult<JSONObject> addArea(@RequestBody GeConGisresourceArea geConGisresourceArea){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geConGisresourceAreaService.insert(geConGisresourceArea);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 编辑区域
     */
    @PostMapping(value = "/editArea")
    public CommonResult<JSONObject> editArea(@RequestBody GeConGisresourceArea geConGisresourceArea){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geConGisresourceAreaService.update(geConGisresourceArea);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除区域
     */
    @PostMapping(value = "/deleteArea")
    public CommonResult<JSONObject> deleteArea(int areaId){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geConGisresourceAreaService.deleteById(areaId);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return  result;
    }

    /**
     * 获取全部区域
     */
    @GetMapping(value = "/arealist")
    public CommonResult<List<GeConGisresourceArea>> arealist(){
        CommonResult<List<GeConGisresourceArea>> result = new CommonResult<>();
        try {
            List<GeConGisresourceArea> list=geConGisresourceAreaService.queryAllByLimit(0,0);
            result.setCode(200);
            result.setData(list);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    @GetMapping(value = "/getGis")
    @ApiOperation("获取所有点")
    public CommonResult<List<ValueLabel>> getGis(String value){
        CommonResult<List<ValueLabel>> result = new CommonResult<>();
        try {
            List<ValueLabel> list=geConGisresourceAreaService.getGis(value);
            result.setCode(200);
            result.setData(list);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    @GetMapping(value = "/getGisById")
    @ApiOperation("通过id获取所有点")
    public CommonResult<List<GisTitleCoordinate>> getGisById(String gisIds){
        CommonResult<List<GisTitleCoordinate>> result = new CommonResult<>();
        try {
            List<GisTitleCoordinate> gisTitleCoordinates=geConGisresourceAreaService.getGisById(gisIds);
            result.setCode(200);
            result.setData(gisTitleCoordinates);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    @GetMapping(value = "/list2")
    @ApiOperation("通过类型和缩放比例查询")
    public CommonResult<List<GeConGisresource>> list2(@RequestParam(required = true,name = "type") Integer type,
                                                        @RequestParam(required = true,name = "zoom") Integer zoom){
        log.info("gis-通过类型和缩放比例查询：{},{}",type,zoom);
        List<GeConGisresource> result = geConGisresourceService.list2(type,zoom);
        return CommonResult.success("查询成功",result);
    }



}
